(function () {

    "use strict";

    var api = {
        getListsUrl: '/api/car/lists',
        modifyCar: '/api/car/modify',
        modifyNum: '/api/car/modifyNum',
        modifyAll: '/api/car/modifyAll',
        deleteItem: '/api/car/deleteItem',
        carCounter: '/api/car/counter'
    };
    sm.controller('wx-car-index-controller', ['$scope', '$http', 'Modal', 'Toast', function ($scope, $http, Modal, Toast){

        // 全选
        $scope.selectAllItems = false;
        // 所有
        $scope.lists = [];
        // 已选择
        $scope.data = [];
        // 总价
        $scope.total = 0;

        $scope.noGoods = false;

        $scope.loading = true;

        /**
         * 列表
         */
        $scope.getLists = function () {
            $scope.loading = true;
            $http.get(api.getListsUrl).success(function (res) {
                $scope.loading = false;
                if (res.state) {
                    var len = res.data.length;
                    $scope.lists = res.data;
                    $scope.salcPrice();

                    if ($scope.lists.length == 0) {
                        $scope.noGoods = true;
                    }
                }
            });
        };

        function calcCounter() {
            $http.get(api.carCounter).success(function (res) {
                if (res.state) {
                    $scope.carCounter = res.data.total;
                    $scope.$broadcast('carCounter', res.data.total);
                }
            });
        }

        /**
         * 选择
         * @param index
         * @returns {boolean}
         */
        $scope.select = function(index) {
            var goodsId = $scope.lists[index]['goodsId'],
                selected = $scope.lists[index]['selected'],
                ruleId = $scope.lists[index]['ruleId'],
                newStatus;
            if (!goodsId) {
                return false;
            }

            newStatus = selected == 1 ? 0 : 1;

            Toast.loading();
            $http.post(api.modifyCar, {
                'goodsId': goodsId,
                'ruleId': ruleId,
                'status': newStatus
            }).success(function (res) {
                Toast.stop();
                if (res.state) {
                    $scope.lists[index]['selected'] = newStatus;
                    // 修改价格
                    $scope.salcPrice();
                }
            });
        };

        // 全选
        $scope.salcPrice = function (type) {
            var sum = 0, counter = 0;
            var len = $scope.lists.length;
            angular.forEach($scope.lists, function (val, key) {

                if (type && type == 'yes') {
                    val['selected'] = 1;
                } else if (type && type == 'no') {
                    val['selected'] = 0;
                }

                if (val['selected'] == 1) {
                    counter++;
                    var s = 0;
                    s = accMul(parseInt(val['num']), parseFloat(val['price']) / 100);
                    sum = accAdd(sum, s);
                }
            });

            if (counter == len) {
                $scope.selectAllItems = true;
            } else {
                $scope.selectAllItems = false;
            }

            $scope.total = sum.toFixed(2);
        };

        /**
         * 修改数量
         * @param index
         * @param l
         * @param type
         * @returns {boolean}
         */
        $scope.modifyNum = function (index, l, type) {
            var num = l.num,
                stock = l.stock,
                goodsId = l.goodsId;
            // +
            if (type == 'up') {
                if (num + 1 > stock) {
                    Modal.alert({
                        'title': '提示',
                        'content': '商品库存不足'
                    });
                } else {
                    num++;
                }
            }
            // -
            else {
                if (num <= 1) {
                    return false;
                }

                num--;
            }

            Toast.loading();
            $http.post(api.modifyNum, {
                'goodsId': goodsId,
                'num': num
            }).success(function(res) {
                Toast.stop();
                if (res.state) {
                    // 成功
                    calcCounter();
                    $scope.lists[index]['num'] = num;
                    $scope.salcPrice();
                } else {
                    // 失败
                    Toast.error({title: '网络错误'});
                }
            });

        };

        /**
         * 全选/全不选
         */
        $scope.selectAll = function () {
            $scope.selectAllItems = !$scope.selectAllItems;
            var type = 'no';
            if ($scope.selectAllItems) {
                // 全选
                type = 'yes';
            }

            Toast.loading();
            $http.post(api.modifyAll, {
                type: type
            }).success(function (res) {
                Toast.stop();
                if (res.state) {
                    $scope.salcPrice(type);
                } else {
                    Toast.error({title: '修改失败'});
                }
            });
        };

        /**
         * 删除
         * @param index
         * @param l
         * @returns {boolean}
         */
        $scope.delete = function (index, l) {

            if (!l.goodsId) {
                return false;
            }

            Modal.alert({
                title: '操作提示',
                content: '商品一旦删除将不能恢复',
                buttons:[{
                    name: '取消'
                }, {
                    name: '确认删除',
                    event: function () {
                        doDelete(index);
                    }
                }]
            });

            function doDelete(index) {
                Toast.loading({title: '正在删除'});
                $http.post(api.deleteItem, {
                    goodsId: l['goodsId'],
                    ruleId: l['ruleId']
                }).success(function(res) {
                    Toast.stop();
                    if (res.state) {
                        calcCounter();
                        $scope.lists.splice(index, 1);
                        $scope.salcPrice();
                    }
                }).error(function () {
                    Toast.stop();
                    Toast.error({title: '错误'});
                });
            }
        };

        $scope.editing = false;
        $scope.editModel = function () {
            $scope.editing = !$scope.editing;
            if ($scope.editing) {
                // 修改状态

            } else {
               // 未修改状态
            }
        };

        /**
         * 确认订单
         */
        $scope.goConfirm = function () {
            var willConfirm = false;
            angular.forEach($scope.lists, function (val) {
                if (val.selected) {
                   willConfirm = true;
                }
            });

            if (!willConfirm) {
                Toast.error({title: '您还没有选择商品'});
                return false;
            }

            location.href = '/order/confirm';
        };


        //乘法函数，用来得到精确的乘法结果
        //说明：javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
        //调用：accMul(arg1,arg2)
        //返回值：arg1乘以arg2的精确结果
        function accMul(arg1,arg2)
        {
            var m=0,s1=arg1.toString(),s2=arg2.toString();
            try{m+=s1.split(".")[1].length}catch(e){}
            try{m+=s2.split(".")[1].length}catch(e){}
            return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
        }

        function accAdd(arg1,arg2){
            var r1,r2,m;
            try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
            try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
            m=Math.pow(10,Math.max(r1,r2))
            return (arg1*m+arg2*m)/m
        }

        $scope.getLists();
    }]);
})();

